package com.imflea.zero.service.qx.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.constant.QxContant;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.model.dao.qx.QxRoleUserMapper;
import com.imflea.zero.model.entity.qx.QxRole;
import com.imflea.zero.model.entity.qx.QxRoleUser;
import com.imflea.zero.service.qx.IQxRoleService;
import com.imflea.zero.service.qx.IQxRoleUserService;
import com.imflea.zero.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色用户关联表 服务实现类
 * </p>
 *
 * @author xiangbaoyu
 * @since 2021-08-18
 */
@Service
public class QxRoleUserServiceImpl extends ServiceImpl<QxRoleUserMapper, QxRoleUser> implements IQxRoleUserService {
    @Autowired
    private IQxRoleService qxRoleService;

    @Override
    public Boolean saveRoleUserBatch(String userId, List<String> roleIds) {
        String tenantId = SessionUtils.getTenantId();
        return this.saveRoleUserBatch(userId, roleIds, tenantId);
    }

    @Override
    public Boolean saveRoleUserBatch(String userId, List<String> roleIds, String tenantId) {
        if (CommonUtils.isNull(roleIds)) {
            throw new BizException("请选择需要授权的角色");
        }
        QueryWrapper<QxRoleUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Long count = this.count(queryWrapper);
        boolean oldRoleUsersResult = this.remove(queryWrapper);

        if (count != 0 && !oldRoleUsersResult) {
            throw new BizException("授权失败");
        }
        List<QxRoleUser> roleUsers = new ArrayList<>();
        for (String roleId : roleIds) {
            QxRoleUser roleUser = new QxRoleUser();
            roleUser.setId(CommonUtils.generateRandomString());
            roleUser.setUserId(userId);
            roleUser.setRoleId(roleId);
            roleUser.setTenantId(tenantId);
            roleUsers.add(roleUser);
        }
        boolean result = this.saveOrUpdateBatch(roleUsers);
        if (result) {
            return true;
        } else {
            throw new BizException("授权失败");
        }
    }

    @Override
    public List<QxRoleUser> queryRolesByUserId(String userId) {
        Map<String, Object> csMap = new HashMap<>();
        csMap.put("user_id", userId);
        List<QxRoleUser> result = this.listByMap(csMap);
        return result;
    }

    /**
     * @param userId
     * @return boolean
     * @author 祥保玉
     * @description 校验当前用户是否为租户管理员
     * @date 2021/9/18  17:28
     */


    @Override
    public boolean query4CheckIsTenantAdmin(String userId) {
        List<QxRoleUser> result = this.queryRolesByUserId(userId);

        for (QxRoleUser roleUser : result) {
            if (roleUser.getRoleId().equals(QxContant.getTenantAdminRoleId())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<QxRoleUser> queryRolesByUserIds(List<String> userIds) {
        QueryWrapper<QxRoleUser> qxRoleUserQueryWrapper = new QueryWrapper<>();
        List<QxRoleUser> result = this.list(qxRoleUserQueryWrapper);
        return result;
    }

    public Map<String, List<QxRole>> queryAllRoleByUserIds(List<String> userIds) {
        Map<String, List<QxRole>> result = new HashMap<>();
        List<QxRoleUser> qxRoleUsers = this.queryRolesByUserIds(userIds);
        if (CommonUtils.isNull(qxRoleUsers)) {
            return result;
        }
        Map<String, List<QxRoleUser>> userRolesMap = qxRoleUsers.stream().collect(Collectors.groupingBy(item -> item.getUserId()));
        //all 角色
        List<QxRole> qxRoles = this.qxRoleService.list();
        for (String userId : userIds) {
            List<QxRoleUser> userRoles = userRolesMap.get(userId);
            if (CommonUtils.isNull(userRoles)) {
                userRoles = new ArrayList<>();
            }
            List<QxRole> currentRoles = new ArrayList<>();
            for (QxRoleUser roleUser : userRoles) {
                for (QxRole role : qxRoles) {
                    if (roleUser.getRoleId().equals(role.getId())) {
                        currentRoles.add(role);
                    }

                }
                result.put(userId, currentRoles);
            }
        }
        return result;
    }


}
